﻿using SalesSys.DAL;
using SalesSys.DAL.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SalesSys.BLL
{
   public class AccountsReportBLL
    {
       public List<AccountsReport> GetAccountsReportList(bool isHander, DateTime? startTime, DateTime? endTime, Guid? deptId)
        {
            var sql = "exec Proc_AccountsReport";
            if (startTime.HasValue)
            {
                if (sql.Contains("@"))
                    sql += ",";
                sql += " @StartCreateTime='" + startTime.Value.ToString("yyyy-MM-dd") + "'";
            }
            if (endTime.HasValue)
            {
                if (sql.Contains("@"))
                    sql += ",";
                sql += " @EndCreateTime='" + endTime.Value.ToString("yyyy-MM-dd") + "'";
            }
            if (deptId.HasValue)
            {
                if (sql.Contains("@"))
                    sql += ",";
                sql += "@DepartmentId='" + deptId.Value+"'";
            }

            var rep = RepositoryFactory.GetRepositoryByFactoryUnit<IDepotHistroyRep>();
            var dt = rep.GetTableInfo(sql);
            return FillModel(dt);
        }

        /// <summary>  
        /// 填充对象列表：用DataTable填充实体类
        /// </summary>  
        public List<AccountsReport> FillModel(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return new List<AccountsReport>();
            }
            List<AccountsReport> modelList = new List<AccountsReport>();
            foreach (DataRow dr in dt.Rows)
            {
                AccountsReport model = new AccountsReport();
                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                        propertyInfo.SetValue(model, dr[i], null);
                }

                modelList.Add(model);
            }
            return modelList;
        }
    }
}
